package com.example.pixelyear.view

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View
import com.example.pixelyear.R
import com.example.pixelyear.bean.DateBean
import com.example.pixelyear.utils.NumberUtils
import com.example.pixelyear.utils.UIUtils
import com.example.pixelyear.utils.Utils
import com.socks.library.KLog

/**
 * 小一号的日历控件
 */
class SmallPixelView @JvmOverloads constructor(
    context: Context,
    attributes: AttributeSet? = null,
    defaultStyle: Int = 0
) :
    View(context, attributes, defaultStyle) {

    private var boxWidth = UIUtils.getDimension(R.dimen.dp_15) //宽度
    private var boxHeight = UIUtils.getDimension(R.dimen.dp_15) //高度
    private val boxPadding = 1 //分割线宽度
    private var columnSize = 0//行数
    private var rowSize = 7 //列数
    private var textWeekHeight = 0
    private var textWeekWidth = 0
    private val color75 = UIUtils.getColor(R.color.gray_757575)
    private var lastColor = color75
    private var days = 0
    private var week = 0//星期 用来判断每月一次需要空几格
    private var dimen10 = UIUtils.getDimensionFloat(R.dimen.dp_3) //圆距离边的距离
    private var dimen5 = UIUtils.getDimensionFloat(R.dimen.dp_2) //远的半径
    var month = 0//需要画的月份
    var year = 0 //需要画的年份
    private var nowMonth = 0    //现在年份
    private var nowYear = 0  //现在月份
    private var nowDay = 0  //现在日期 天

    private var nowDayWidth = 0 //今 字的宽度
    private var nowDayHeight = 0 //今 字的高度
    private var moodTextWidth = 0 //表情文字宽度
    private val paint = UIUtils.getString(R.string.paint)

    private val DayPadding = 1
    private val WeekPadding = 2
    private val dateList = mutableListOf<DateBean>()

    private val roundRX = 10f//圆角X半径
    private val roundRY = 10f//圆角Y半径

    //正常日期画笔
    private val boxPaint by lazy {
        Paint().also {
            it.color = color75
            it.flags = Paint.ANTI_ALIAS_FLAG
        }
    }

    //星期文字画笔
    private val textWeekPaint by lazy {
        Paint().also {
            it.color = UIUtils.getColor(R.color.gray_666666)
            it.flags = Paint.ANTI_ALIAS_FLAG
            it.textSize = UIUtils.getDimensionFloat(R.dimen.sp_5)
        }
    }

    //日期文字画笔
    private val textDayPaint by lazy {
        Paint().also {
            it.color = UIUtils.getColor(R.color.white)
            it.flags = Paint.ANTI_ALIAS_FLAG
            it.textSize = UIUtils.getDimensionFloat(R.dimen.sp_3)
        }
    }

    //今天任务标记
    private val nowDayPaint by lazy {
        Paint().also {
            it.color = UIUtils.getColor(R.color.black_999999)
            it.flags = Paint.ANTI_ALIAS_FLAG
            it.textSize = UIUtils.getDimensionFloat(R.dimen.sp_2)
        }
    }

    private val roundRectF by lazy {
        RectF()
    }

    //今天任务标记
    private val moodPaint by lazy {
        Paint().also {
            it.color = UIUtils.getColor(R.color.black_999999)
            it.flags = Paint.ANTI_ALIAS_FLAG
            it.typeface = UIUtils.getTextFont(context)
            it.textSize = UIUtils.getDimensionFloat(R.dimen.sp_3)
        }
    }

    private val weekRect by lazy {
        Rect()
    }

    private val dayRect by lazy {
        Rect()
    }

    private val nowDayRect by lazy {
        Rect()
    }

    private val moodRect by lazy {
        Rect()
    }

    init {
        initTextWidth()
        initTime()
    }

    private fun initTextWidth() {
        textWeekPaint.getTextBounds("五", 0, "五".length, weekRect)
        textWeekHeight = weekRect.height()
        textWeekWidth = weekRect.width()

        nowDayPaint.getTextBounds("今", 0, "今".length, nowDayRect)
        //计算今字的上左间距
        nowDayHeight = (nowDayRect.height() * 1.5).toInt()
        nowDayWidth = nowDayRect.width()

        moodPaint.getTextBounds(paint, 0, paint.length, moodRect)
        moodTextWidth = moodRect.width()

    }

    private fun initTime() {
        if (month == 0 || year == 0) return
        nowMonth = Utils.getMonth()
        nowYear = Utils.getYear()
        nowDay = Utils.getDay()
        week = Utils.dateTranslateWeek("$year-$month-01") - 1
        days = month.let {
            if (it == 1 || it == 3 || it == 5 || it == 7 || it == 8 || it == 10 || it == 12) {
                31
            } else if (it == 2) {
                if ((year / 100 != 0 && year / 4 == 0) || (year / 100 == 0 && year / 400 == 0)) {
                    29
                } else 28
            } else {
                30
            }
        }
        columnSize = if ((days + week) % 7 == 0) (days + week) / 7 else (days + week) / 7 + 1
//        KLog.e("yxs", "计算的多少行：$year 年$month 月 行数$columnSize ===$week ===天数$days")
    }


    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        val widthMode = MeasureSpec.getMode(widthMeasureSpec)
        val heightMode = MeasureSpec.getMode(heightMeasureSpec)
        var w = 0
        var h = 0

        if (widthMode == MeasureSpec.AT_MOST || heightMode == MeasureSpec.UNSPECIFIED) {
            w = boxWidth * rowSize + boxPadding
        }

        if (heightMode == MeasureSpec.AT_MOST || heightMode == MeasureSpec.UNSPECIFIED) {
            //加一是加上星期行的高度
            h = boxHeight * (columnSize + 1) + boxPadding
        }
//        KLog.e("yxs", "高度宽度：" + w + "===" + h + " ===月份$month")
        setMeasuredDimension(w, h)
    }

    override fun onDraw(canvas: Canvas?) {
        for (i in 0 until columnSize) {
            for (j in 0 until rowSize) {
                //画星期
                canvas?.drawText(
                    NumberUtils.translateWeek(j + 1),
                    (boxWidth * j).toFloat() + getTextRightPadding(WeekPadding)
                    ,
                    boxHeight.toFloat() - getTextTopPadding(WeekPadding),
                    textWeekPaint
                )

                val thisDay = (i * rowSize) + j + 1
                if (thisDay - week <= days && thisDay > week) {
                    val filter = dateList.filter { it.day == (thisDay - week) }
                    if (filter.isNotEmpty()) {
                        if (lastColor != filter[0].color) {
                            lastColor = filter[0].color
                            boxPaint.color = lastColor
                            textDayPaint.color = filter[0].textColor
                            nowDayPaint.color = filter[0].textColor
                            moodPaint.color = filter[0].textColor
                        }
                        //画有标记的日期
                        roundRectF.left = (boxWidth * j).toFloat() + boxPadding
                        roundRectF.top = (boxHeight * i).toFloat() + boxPadding + boxHeight
                        roundRectF.right = ((boxWidth) * (j + 1)).toFloat()
                        roundRectF.bottom = ((boxHeight) * (i + 1)).toFloat() + boxHeight
                        canvas?.drawRoundRect(
                            roundRectF, roundRX, roundRY, boxPaint
                        )

                        //画心情
                        canvas?.drawText(
                            filter[0].mood,
                            (boxWidth * j).toFloat() + boxPadding + (boxWidth - moodTextWidth) / 2,
                            ((boxHeight) * (i + 1)).toFloat() + boxHeight - dimen5,
                            moodPaint
                        )

                        //画有任务标记
                        if (filter[0].note.isNotEmpty()) {
                            canvas?.drawText(
                                paint,
                                ((boxWidth) * (j + 1)).toFloat() - dimen10 - dimen5,
                                ((boxHeight) * (i + 1)).toFloat() + boxHeight - dimen5,
                                moodPaint
                            )
                        }
                    } else {
                        if (lastColor != color75) {
                            lastColor = color75
                            boxPaint.color = lastColor

                            textDayPaint.color = Color.WHITE
                            nowDayPaint.color = Color.WHITE
                        }
                        //画没有记录的日期
                        roundRectF.left = (boxWidth * j).toFloat() + boxPadding
                        roundRectF.top = (boxHeight * i).toFloat() + boxPadding + boxHeight
                        roundRectF.right = ((boxWidth) * (j + 1)).toFloat()
                        roundRectF.bottom = ((boxHeight) * (i + 1)).toFloat() + boxHeight
                        canvas?.drawRoundRect(
                            roundRectF, roundRX, roundRY, boxPaint
                        )

                    }

                    //画日期文字
                    with((thisDay - week).toString()) {
                        textDayPaint.getTextBounds(this, 0, length, dayRect)

                        canvas?.drawText(
                            this,
                            (boxWidth * j).toFloat() + boxPadding + getTextRightPadding(DayPadding),
                            ((boxHeight) * (i + 1)).toFloat() + boxHeight - getTextTopPadding(
                                DayPadding
                            ), textDayPaint
                        )
                    }

                }

                if (year == nowYear && month == nowMonth && (thisDay - week) == nowDay) {
                    KLog.e("yxs", "日期：$thisDay===$nowDay===$j====$i")
                    canvas?.drawText(
                        "今",
                        (boxWidth * j).toFloat() + boxPadding + nowDayWidth,
                        ((boxHeight) * (i + 1)).toFloat() + nowDayHeight,
                        nowDayPaint
                    )
                }

            }
        }

    }


    private fun getTextTopPadding(flag: Int): Float {
        return if (flag == DayPadding)
            ((boxHeight - dayRect.height()) / 2).toFloat()
        else
            ((boxHeight - textWeekWidth) / 2).toFloat()
    }

    private fun getTextRightPadding(flag: Int): Float {
        return if (flag == DayPadding)
            ((boxWidth - dayRect.width()) / 2).toFloat()
        else
            ((boxWidth - textWeekWidth) / 2).toFloat()
    }

    fun updateMonthAndYear(month: Int, year: Int) {
        this.month = month
        this.year = year
        initTime()
        requestLayout()
    }

    fun updateDateList(list: MutableList<DateBean>) {
        dateList.clear()
        dateList.addAll(list)
        invalidate()
    }

}
